package service

import (
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/repository"
	"gitee.com/ling1314/origin-utility/utils"
	"gorm.io/gorm"
)

type deptService struct {
	baseService
}

func (ser deptService) Add(argus *model.DeptForm, self *utils.CustomClaims) error {
	return db.GetDB().Transaction(func(tx *gorm.DB) error {
		var (
			err error
		)
		t := &model.Dept{
			DeptId:         utils.GetSoftId(),
			DeptName:       argus.DeptName,
			ParentId:       argus.ParentId,
			MaxUserNum:     argus.MaxUserNum,
			BalanceUserNum: argus.MaxUserNum,
			Status:         argus.Status,
			Creator:        self.Nickname,
			CreatorId:      self.UserID,
		}
		// 插入团队数据
		if err = repository.DeptRepository.Create(t); err != nil {
			return err
		}
		return nil
	})

}

func (ser deptService) Update(argus *model.DeptForm) error {
	return db.GetDB().Transaction(func(tx *gorm.DB) error {
		var (
			err   error
			dDept *model.Dept
		)
		if dDept, err = repository.DeptRepository.FindById(argus.DeptId); err != nil {
			return err
		}
		dDept.Status = argus.Status
		dDept.ParentId = argus.ParentId
		dDept.DeptName = argus.DeptName
		if err = repository.DeptRepository.UpdateById(dDept); err != nil {
			return err
		}
		return nil
	})
}

func (ser deptService) FindAll(argus *model.SearchDept) (li []*model.Dept, err error) {
	if li, err = repository.DeptRepository.FindAll(argus.DeptName); err != nil {
		return
	}
	return li, nil
}

func (ser deptService) Delete(deptId int64, del bool) error {
	return db.GetDB().Transaction(func(tx *gorm.DB) error {
		var (
			err   error
			uList []*model.User
			uIds  []int64
		)
		if err = repository.DeptRepository.DeleteById(deptId); err != nil {
			return err
		}
		if uList, _, err = repository.UserRepository.FindListByDepId(deptId); err != nil {
			return err
		}
		uIds = make([]int64, len(uList))
		for i := range uList {
			uIds[i] = uList[i].UserId
		}
		if del {
			if err = repository.UserRepository.DeleteByIds(uIds); err != nil {
				return err
			}
		} else {
			if err = repository.DeptRepository.UpdateUserDeptId(uIds, model.DeptIdForNothing); err != nil {
				return err
			}
		}
		return nil
	})
}
